﻿#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;

namespace UFrame
{
    public class SpriteSplit
    {
        [MenuItem("Plateface/2D/导出精灵")]
        static void SaveSprite()
        {
            string resourcesPath = "Assets/Resources/";
            foreach (Object obj in Selection.objects)
            {
                string selectionPath = AssetDatabase.GetAssetPath(obj);

                string selectionExt = Path.GetExtension(selectionPath);
                if (selectionExt.Length == 0)
                {
                    continue;
                }

                // 从路径"Assets/Resources/UI/testUI.png"得到路径"UI/testUI"
                string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
                loadPath = loadPath.Substring(resourcesPath.Length);

                // 加载此文件下的所有资源
                Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath);
                if (sprites == null || sprites.Length == 0)
                {
                    Object[] objAry = AssetDatabase.LoadAllAssetsAtPath(selectionPath);
                    sprites = new Sprite[objAry.Length];
                    for (int i = 0; i < objAry.Length; i++)
                    {
                        sprites[i] = objAry[i] as Sprite;
                        //string s = AssetDatabase.GetAssetPath(sprites[i]);
                        //TextureImporter texture = AssetImporter.GetAtPath(s) as TextureImporter;
                        //var defaultSet = texture.GetDefaultPlatformTextureSettings();
                    }
                }

                if (sprites.Length > 0)
                {
                    // 创建导出文件夹
                    string outPath = Application.dataPath + "/outSprite/" + loadPath;
                    Directory.CreateDirectory(outPath);

                    foreach (Sprite sprite in sprites)
                    {
                        if (sprite == null)
                        {
                            continue;
                        }

                        // 创建单独的纹理
                        Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height,
                            sprite.texture.format, false);

                        tex.SetPixels(sprite.texture.GetPixels(
                            (int)sprite.rect.xMin,
                            (int)sprite.rect.yMin,
                            (int)sprite.rect.width,
                            (int)sprite.rect.height));

                        tex.Apply();

                        // 写入成PNG文件
                        File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
                    }

                    Debug.Log("SaveSprite to " + outPath);
                }
            }
        }
    }
}
#endif